import { Schema } from 'mongoose';
import { IUserAction } from '../types/IUserAction';

export const UserActionSchema = new Schema<IUserAction>({
  userId: { type: String, required: true, index: true },
  sessionId: { type: String, sparse: true, index: true },
  action: {
    type: String,
    enum: ['create_session', 'send_message', 'upload_file', 'delete_message', 'search', 'export'],
    required: true,
    index: true
  },
  details: {
    target: { type: String },
    parameters: { type: Schema.Types.Mixed },
    result: {
      type: String,
      enum: ['success', 'error', 'partial']
    },
    errorMessage: { type: String }
  },
  userAgent: { type: String },
  ipAddress: { type: String },
  duration: { type: Number, min: 0 }
}, {
  timestamps: true,
  collection: 'user_actions'
});

// Compound Indexes
UserActionSchema.index({ userId: 1, createdAt: -1 });
UserActionSchema.index({ action: 1, createdAt: -1 });
UserActionSchema.index({ sessionId: 1, action: 1 }, { sparse: true });
UserActionSchema.index({ 'details.result': 1, createdAt: -1 });

// TTL Index
UserActionSchema.index({ createdAt: 1 }, { expireAfterSeconds: 7776000 }); // 90 days
